package kr.hkit.powerjava.chapter26.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

import kr.hkit.powerjava.chapter26.dao.DepartmentDAO;
import kr.hkit.powerjava.chapter26.dao.InterfaceDAO;
import kr.hkit.powerjava.chapter26.dto.Department;

public class DepartmentService extends AbsService<Department>{
	private ArrayList<Department> list;
	public DepartmentService(Scanner sc, Connection connection) {
		super(sc, connection);
		dao = new DepartmentDAO(connection);
		
	}

	@Override
	public Department inputItemInfo(boolean gubun) {
		System.out.print("학과번호 학과명");
		Department dept = new Department(sc.nextInt(), sc.next().trim());
		if(gubun) {
			System.out.print("위치");
			int floor = sc.nextInt();
			dept.setFloor(floor);
		}
		return dept;
	}

	@Override
	public void prnSubMenu() {
		System.out.println("1.이름순 정렬2.위치순정렬 3.번호별 정렬");
		try {
			list = dao.listItems();
			int res = sc.nextInt();
			switch(res) {
				case 1:
					prnListItem(new Comparator<Department>() {
						@Override
						public int compare(Department o1, Department o2) {
							return o1.getDeptName().hashCode()- o2.getDeptName().hashCode();
						}
					});
					break;
				case 2:
					prnListItem(new Comparator<Department>() {
						@Override
						public int compare(Department o1, Department o2) {
							return o1.getFloor() - o2.getFloor();
						}
					});
					break;
				default :
					prnListItem(null);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private void prnListItem(Comparator<Department> comparator) {
		if(comparator == null) {
			Collections.sort(list);
			prnList(list);
		} else {
			Collections.sort(list, comparator);
			prnList(list);
		}
	}

	private void prnList(ArrayList<Department> list) {
		for(Department d : list) {
			System.out.println(d);
		}
	}	
}